<template>
  <div class="class-management">
    <!-- 搜索和操作区 -->
    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="searchKeyword" placeholder="搜索班级名称/编号" clearable></el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchGrade" placeholder="选择年级">
            <el-option label="全部" value=""></el-option>
            <el-option label="一年级" value="1"></el-option>
            <el-option label="二年级" value="2"></el-option>
            <el-option label="三年级" value="3"></el-option>
            <el-option label="四年级" value="4"></el-option>
            <el-option label="五年级" value="5"></el-option>
            <el-option label="六年级" value="6"></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchSchool" placeholder="选择学校">
            <el-option label="全部" value=""></el-option>
            <el-option v-for="school in schools" :key="school.number" :label="school.name" :value="school.number"></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-col>
        <el-col :span="4" class="text-right">
          <el-button type="success" @click="openAddClassDialog">
            <el-icon><Plus /></el-icon> 添加班级
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 班级列表 -->
    <el-card class="class-list-card">
      <template #header>
        <span>班级管理</span>
        <span class="count">(共 {{ filteredClasses.length }} 个班级)</span>
      </template>
      
      <el-table :data="filteredClasses" border v-loading="loading">
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="name" label="班级名称" width="150"></el-table-column>
        <el-table-column prop="id" label="班级ID" width="70"></el-table-column>
        <el-table-column prop="grade" label="年级"></el-table-column>
        <el-table-column prop="headTeacherId" label="班主任"></el-table-column>
<el-table-column label="操作" width="300">
  <template #default="scope">
    <el-button size="small" @click="handleViewStudents(scope.row)">查看学生</el-button>
    <el-button size="small" type="primary" @click="openEditClassDialog(scope.row)">编辑</el-button>
    <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
    <!-- 新增选择代课老师按钮 -->
    <el-button size="small" type="info" @click="openSelectTeacherDialog(scope.row)">代课老师</el-button>
  </template>
</el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredClasses.length"
        ></el-pagination>
      </div>
    </el-card>
    <!-- 选择代课老师弹窗 -->
    <el-dialog 
      title="选择代课老师" 
      v-model="selectTeacherDialogVisible" 
      width="600px"
    >
      <el-form 
        :model="classForm" 
        :rules="teacherRules" 
        ref="teacherFormRef"
        label-width="100px"
      >
        <el-form-item label="班级ID" prop="id">
          <el-input v-model="classForm.id" disabled placeholder="班级ID"></el-input>
        </el-form-item>
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="classForm.name" disabled placeholder="班级名称"></el-input>
        </el-form-item>
        <el-form-item label="语文老师" prop="chineseTeacher">
          <el-select 
            v-model="classForm.courseTeachers.chinese" 
            filterable
            remote
            reserve-keyword
            placeholder="请选择语文老师"
            :remote-method="handleTeacherSearch"
            :loading="teacherLoading"
          >
            <el-option 
              v-for="teacher in filteredTeachers" 
              :key="teacher.teacherId" 
              :label="teacher.teacherId" 
              :value="teacher.teacherId"
            />
          </el-select>
          <el-button type="primary" @click="submitTeacherSelection">修改</el-button>
        </el-form-item>
        <el-form-item label="数学老师" prop="mathTeacher">
          <el-select 
            v-model="classForm.courseTeachers.math" 
            filterable
            remote
            reserve-keyword
            placeholder="请选择数学老师"
            :remote-method="handleTeacherSearch"
            :loading="teacherLoading"
          >
            <el-option 
              v-for="teacher in filteredTeachers" 
              :key="teacher.teacherId" 
              :label="teacher.teacherId" 
              :value="teacher.teacherId"
            />
          </el-select>
          <el-button type="primary" @click="submitTeacherSelection">修改</el-button>
        </el-form-item>
        <el-form-item label="英语老师" prop="englishTeacher">
          <el-select 
            v-model="classForm.courseTeachers.english" 
            filterable
            remote
            reserve-keyword
            placeholder="请选择英语老师"
            :remote-method="handleTeacherSearch"
            :loading="teacherLoading"
          >
            <el-option 
              v-for="teacher in filteredTeachers" 
              :key="teacher.teacherId" 
              :label="teacher.teacherId" 
              :value="teacher.teacherId"
            />
          </el-select>
          <el-button type="primary" @click="submitTeacherSelection">修改</el-button>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button type="primary" @click="selectTeacherDialogVisible = false">确定</el-button>
      </template>
    </el-dialog>
    

    <!-- 班级学生弹窗 -->
    <el-dialog 
      title="班级学生列表" 
      v-model="studentDialogVisible" 
      width="800px"
    >
      <el-input 
        v-model="studentSearchKeyword" 
        placeholder="搜索学生姓名/学号" 
        clearable 
        style="margin-bottom: 15px;"
      ></el-input>
      
      <el-table :data="filteredStudents" border v-loading="studentLoading">
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="realName" label="姓名" width="120"></el-table-column>
        <el-table-column prop="number" label="学号" width="150"></el-table-column>
        <el-table-column prop="userNum" label="监护人"></el-table-column>
        <el-table-column label="操作" width="134">
          <template #default="scope">
            <el-button size="small" @click="openStudentDetailDialog(scope.row.id)">详情</el-button>
            <el-button size="small" type="danger" @click="handleDeleteStudent(scope.row.idCard)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <template #footer>
        <el-button @click="studentDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="openAddStudentDialog">添加学生</el-button>
      </template>
    </el-dialog>

    <!-- 学生详情弹窗 -->
    <el-dialog 
      title="学生详情" 
      v-model="studentDetailDialogVisible" 
      width="500px"
      :before-close="closeStudentDetailDialog"
    >
      <el-descriptions 
        :model="currentStudent" 
        border 
        column="1" 
        label-width="120px"
        style="margin-top: 20px;"
      >
        <el-descriptions-item label="学生姓名">{{ currentStudent.realName }}</el-descriptions-item>
        <el-descriptions-item label="学号">{{ currentStudent.number }}</el-descriptions-item>
        <el-descriptions-item label="昵称">{{ currentStudent.nickName || '未设置' }}</el-descriptions-item>
        <el-descriptions-item label="学籍号">{{ currentStudent.idCard || '未填写' }}</el-descriptions-item>
        <el-descriptions-item label="监护人">{{ currentStudent.usernum || '未填写' }}</el-descriptions-item>
        <el-descriptions-item label="所属班级">
          {{ getClassNameByClassId(currentStudent.classId) }}
        </el-descriptions-item>
        <el-descriptions-item label="账户状态">
          <el-tag :type="currentStudent.status === 1 ? 'success' : 'danger'">
            {{ currentStudent.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="最后登录时间">
          {{ currentStudent.lastLoginTime ? formatDate(currentStudent.lastLoginTime) : '未登录' }}
        </el-descriptions-item>
      </el-descriptions>
      
      <template #footer>
        <el-button @click="studentDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 添加班级弹窗 -->
    <el-dialog 
      title="添加班级" 
      v-model="addClassDialogVisible" 
      width="500px"
    >
      <el-form 
        :model="classForm" 
        :rules="classRules" 
        ref="classFormRef"
        label-width="100px"
      >
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="classForm.name" placeholder="请输入班级名称（如三年级二班）"></el-input>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-select v-model="classForm.grade" placeholder="请选择年级">
            <el-option label="一年级" value="1"></el-option>
            <el-option label="二年级" value="2"></el-option>
            <el-option label="三年级" value="3"></el-option>
            <el-option label="四年级" value="4"></el-option>
            <el-option label="五年级" value="5"></el-option>
            <el-option label="六年级" value="6"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班主任" prop="headTeacher">
          <el-select 
            v-model="classForm.headTeacherId" 
            filterable
            remote
            reserve-keyword
            placeholder="请选择或输入班主任"
            :remote-method="handleTeacherSearch"
            :loading="teacherLoading"
          >
            <el-option 
              v-for="teacher in filteredTeachers" 
              :key="teacher.teacherId" 
              :label="teacher.teacherId" 
              :value="teacher.teacherId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="addClassDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddClass">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑班级弹窗 -->
    <el-dialog 
      title="编辑班级" 
      v-model="editClassDialogVisible" 
      width="500px"
    >
      <el-form 
        :model="classForm" 
        :rules="classRules" 
        ref="classFormRef"
        label-width="100px"
      >
        <el-form-item label="班级ID" prop="id">
          <el-input v-model="classForm.id" disabled placeholder="班级ID"></el-input>
        </el-form-item>
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="classForm.name" placeholder="请输入班级名称（如三年级二班）"></el-input>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-select v-model="classForm.grade" placeholder="请选择年级">
            <el-option label="一年级" value="1"></el-option>
            <el-option label="二年级" value="2"></el-option>
            <el-option label="三年级" value="3"></el-option>
            <el-option label="四年级" value="4"></el-option>
            <el-option label="五年级" value="5"></el-option>
            <el-option label="六年级" value="6"></el-option>
          </el-select>
        </el-form-item>
  <el-form-item label="班主任" prop="headTeacherId">
    <el-select 
      v-model="classForm.headTeacherId" 
      filterable
      remote
      reserve-keyword
      placeholder="请选择班主任"
      :remote-method="handleTeacherSearch"
      :loading="teacherLoading"
    >
      <el-option 
        v-for="teacher in filteredTeachers" 
        :key="teacher.teacherId" 
        :label="`${teacher.realName} (${teacher.teacherId})`" 
        :value="teacher.teacherId"
      />
    </el-select>
  </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="editClassDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditClass">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加学生到班级弹窗 -->
    <el-dialog 
      title="添加学生到班级" 
      v-model="addStudentDialogVisible" 
      width="600px"
    >
      <el-form 
        :model="studentForm" 
        :rules="studentRules" 
        ref="studentFormRef"
        label-width="100px"
      >
        <el-form-item label="学籍号" prop="idCard">
          <el-input v-model="studentForm.idCard" placeholder="请输入学籍号"></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="addStudentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddStudent">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { 
  getClassListByschoolNum, 
  getStudentListByClassId, 
  updateClass, 
  deleteClass, 
  deleteStudent, 
  addClass, 
  addStudent,
  getTeacherListByschoolNum,
  getTeacherListByClassId,
  updateSubjectTeacherByClassId
} from '../../../api/school-student/school-student.js';
import { useLoginStore } from '../../../stores/index.js';
import { studentRegister } from '../../../api/login/login.js';

// 搜索条件
const searchKeyword = ref('');
const searchGrade = ref('');
const searchSchool = ref('');
const studentSearchKeyword = ref('');

// 弹窗控制
const studentDialogVisible = ref(false);
const addClassDialogVisible = ref(false);
const editClassDialogVisible = ref(false);
const addStudentDialogVisible = ref(false);
const studentDetailDialogVisible = ref(false);

// 加载状态
const loading = ref(false);
const studentLoading = ref(false);
const teacherLoading = ref(false);

// 数据存储
const classes = ref([]);
const classStudents = ref([]);
const filteredTeachers = ref([]);

// 学生详情数据
const currentStudent = ref({});
const currentClass = ref(null);
const currentClassId = ref(null);

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);

// 表单引用
const classFormRef = ref(null);
const studentFormRef = ref(null);

const teacherFormRef = ref(null);

// 班级表单数据
const classForm = reactive({
  id: null,
  name: '',           // 班级名称
  grade: '',          // 年级
  schoolNum: '',      // 学校编号
  headTeacherId: ''  // 班主任ID
});

// 学生表单数据
const studentForm = reactive({
  id: null,
  number: '',
  password: '',
  realName: '',
  idCard: '',
  usernum: '',
  guardianCard: '',
  nickName: '',
  avatar: '',
  schoolNum: '',
  classId: null,
  age: null,
  gender: '',
  phone: '',
  status: 1
});

// 学校数据
const schools = ref([
  { number: 'S001', name: '第一实验小学' },
  { number: 'S002', name: '第二实验小学' }
]);

// 表单验证规则
const classRules = {
  name: [
    { required: true, message: '请输入班级名称', trigger: 'blur' },
    { min: 2, max: 20, message: '班级名称长度必须在2-20个字符之间', trigger: 'blur' }
  ],
  grade: [
    { required: true, message: '请选择年级', trigger: 'change' }
  ],
  headTeacherId: [
    { required: true, message: '请选择班主任', trigger: 'blur' },
    { pattern: /^\S+$/, message: '班主任ID不能为空字符', trigger: 'blur' }
  ]
};

const studentRules = {
  realName: [
    { required: true, message: '请输入学生姓名', trigger: 'blur' }
  ],
  number: [
    { required: true, message: '请输入学号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请设置密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', message: '年龄必须为数字', trigger: 'blur' },
    { min: 5, max: 15, message: '年龄必须在5到15之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入监护人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ]
};
// 弹窗控制
const selectTeacherDialogVisible = ref(false);

// 代课老师表单验证规则
/* const teacherRules = {
  chineseTeacher: [
    { required: true, message: '请选择语文老师', trigger: 'blur' }
  ],
  mathTeacher: [
    { required: true, message: '请选择数学老师', trigger: 'blur' }
  ],
  englishTeacher: [
    { required: true, message: '请选择英语老师', trigger: 'blur' }
  ]
}; */

// 打开选择代课老师弹窗
const openSelectTeacherDialog = async (cls) => {
  classForm.id = cls.id;
  classForm.name = cls.name;
  
  try {
    // 加载当前班级已设置的代课老师
    const response = await getTeacherListByClassId(cls.id);
    const teachers = response.data || [];
    
    // 初始化课程老师对象
    classForm.courseTeachers = {
      chinese: '',
      math: '',
      english: ''
    };
    
    // 遍历获取到的老师信息，分配到对应课程
    teachers.forEach(teacher => {
      if (teacher.courseName === 'chinese') {
        classForm.courseTeachers.chinese = teacher.teacherId;
      } else if (teacher.courseName === 'math') {
        classForm.courseTeachers.math = teacher.teacherId;
      } else if (teacher.courseName === 'english') {
        classForm.courseTeachers.english = teacher.teacherId;
      }
    });
    
    selectTeacherDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取代课老师信息失败：' + error.message);
  }
};


// 提交代课老师选择
const submitTeacherSelection = async () => {
  try {
    await teacherFormRef.value.validate();
    const classId = classForm.id;
    
    // 显示加载动画
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '保存中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    // 对每门课程的老师分别提交更新
    const courseTypes = [
      {type: 'chinese', name: '语文'},
      {type: 'math', name: '数学'},
      {type: 'english', name: '英语'}
    ];
    
    // 依次更新每门课程的老师
    for (const course of courseTypes) {
      await updateSubjectTeacherByClassId(
        classId,
        course.type,
        classForm.courseTeachers[course.type]
      );
    }
    
    ElMessage.success('代课老师设置成功');
    selectTeacherDialogVisible.value = false;
    fetchClasses(); // 重新获取班级列表
    loadingInstance.close();
  } catch (error) {
    ElMessage.error('设置失败：' + error.message);
  }
};

// 筛选班级
const filteredClasses = computed(() => {
  return classes.value.filter(cls => {
    const keywordMatch = !searchKeyword.value || 
      cls.name.includes(searchKeyword.value) || 
      cls.id.toString().includes(searchKeyword.value);
    const gradeMatch = !searchGrade.value || cls.grade === searchGrade.value;
    const schoolMatch = !searchSchool.value || cls.schoolNum === searchSchool.value;
    return keywordMatch && gradeMatch && schoolMatch;
  });
});

// 筛选当前班级的学生
const filteredStudents = computed(() => {
  if (!currentClass.value) return [];
  
  let result = classStudents.value.filter(student => 
    student.classId === currentClass.value.id
  );
  
  // 搜索学生
  if (studentSearchKeyword.value) {
    result = result.filter(student => 
      student.realName.includes(studentSearchKeyword.value) || 
      student.number.includes(studentSearchKeyword.value)
    );
  }
  
  return result;
});

// 页面加载时获取班级数据
onMounted(() => {
  fetchClasses();
});

// 获取班级列表
const fetchClasses = async () => {
  try {
    loading.value = true;
    const loginStore = useLoginStore();
    const schoolNum = loginStore.user.number;
    const response = await getClassListByschoolNum(schoolNum);
    classes.value = response.data;
  } catch (error) {
    ElMessage.error('获取班级列表失败：' + error.message);
  } finally {
    loading.value = false;
  }
};

// 获取班级学生列表
const fetchClassStudents = async (classId) => {
  try {
    studentLoading.value = true;
    const response = await getStudentListByClassId(classId);
    classStudents.value = response.data;
  } catch (error) {
    ElMessage.error('获取学生列表失败：' + error.message);
  } finally {
    studentLoading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  fetchClasses();
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 查看班级学生
const handleViewStudents = (cls) => {
  currentClass.value = cls;
  currentClassId.value = cls.id;
  studentSearchKeyword.value = '';
  studentDialogVisible.value = true;
  fetchClassStudents(cls.id);
};

// 打开编辑班级弹窗
const openEditClassDialog = (cls) => {
  classForm.id = cls.id;
  classForm.name = cls.name;
  classForm.grade = cls.grade;
  classForm.schoolNum = cls.schoolNum;
  classForm.headTeacherId = cls.headTeacherId;
  editClassDialogVisible.value = true;
};

// 提交编辑班级
const submitEditClass = async () => {
  try {
    await classFormRef.value.validate();
    const params = {
      name: classForm.name,
      grade: classForm.grade,
      headTeacherId: classForm.headTeacherId
    };

    const loadingInstance = ElLoading.service({
      lock: true,
      text: '保存中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
console.log("params=",params);
    const result = await updateClass(classForm.id, params);
    if (result > 0) {
      ElMessage.success('编辑班级成功');
      editClassDialogVisible.value = false;
      fetchClasses();
    } else {
      ElMessage.error('编辑班级失败');
    }
    loadingInstance.close();
  } catch (error) {
    ElMessage.error('编辑失败：' + error.message);
  }
};

// 删除班级
const handleDelete = async (classId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个班级吗？请确保班级下无学生才能删除成功！！！',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const result = await deleteClass(classId);
    if (result > 0) {
      ElMessage.success('删除成功');
      fetchClasses();
    } else {
      ElMessage.error('删除失败');
    }
  } catch (error) {
    if (error.toString() !== 'Cancel') {
      ElMessage.error('删除失败：' + error.message);
    }
  }
};

// 打开添加班级弹窗
const openAddClassDialog = () => {
  classFormRef.value?.resetFields();
  classForm.id = null;
  addClassDialogVisible.value = true;
};

// 提交添加班级
// src/views/school/student/student.vue 中修改submitAddClass方法
const submitAddClass = async () => {
  try {
    await classFormRef.value.validate();
    
    // 补充学校编号（从登录信息获取）
    const loginStore = useLoginStore();
    classForm.schoolNum = loginStore.user.number;
    
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '添加中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    // 确保只传递必要的字段
    const classData = {
      name: classForm.name,
      grade: classForm.grade,
      headTeacherId: classForm.headTeacherId,
      schoolNum: classForm.schoolNum
    };
    
    const result = await addClass(classData);
    if (result > 0) {
      ElMessage.success('添加班级成功');
      addClassDialogVisible.value = false;
      fetchClasses(); // 重新获取班级列表
      classFormRef.value.resetFields(); // 重置表单
    } else {
      ElMessage.error('添加班级失败');
    }
    loadingInstance.close();
  } catch (error) {
    ElMessage.error('添加失败：' + error.message);
  }
};

// 打开添加学生弹窗
const openAddStudentDialog = () => {
  studentFormRef.value?.resetFields();
  studentForm.classId = currentClassId.value;
  studentForm.schoolNum = currentClass.value?.schoolNum;
  addStudentDialogVisible.value = true;
};

// 提交添加学生
const submitAddStudent = async () => {
  try {
    await studentFormRef.value.validate();

    // 添加到班级
    console.log("classId=====>",studentForm.classId);
    console.log("idCard=====>",studentForm.idCard);
    const result = await addStudent(studentForm.idCard, studentForm.classId);
    if (result > 0) {
      ElMessage.success('学生添加成功');
      addStudentDialogVisible.value = false;
      fetchClassStudents(studentForm.classId);
      
      // 更新班级学生数量
      const classIndex = classes.value.findIndex(c => c.id === studentForm.classId);
      if (classIndex !== -1) {
        classes.value[classIndex].studentCount++;
      }
    } else {
      ElMessage.error('添加学生到班级失败');
    }
  } catch (error) {
    ElMessage.error('添加失败：' + error.message);
  }
};

// 打开学生详情弹窗
const openStudentDetailDialog = (studentId) => {
  const student = classStudents.value.find(s => s.id === studentId);
  if (student) {
    currentStudent.value = { ...student };
    studentDetailDialogVisible.value = true;
  } else {
    ElMessage.warning('未找到该学生数据');
  }
};

// 关闭学生详情弹窗
const closeStudentDetailDialog = () => {
  studentDetailDialogVisible.value = false;
  currentStudent.value = {};
};

// 删除学生
const handleDeleteStudent = async (studentIdCard) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个学生吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const result = await deleteStudent(studentIdCard);
    if (result > 0) {
      ElMessage.success('删除成功');
      fetchClassStudents(currentClassId.value);
      
      // 更新班级学生数量
      const classIndex = classes.value.findIndex(c => c.id === currentClassId.value);
      if (classIndex !== -1) {
        classes.value[classIndex].studentCount--;
      }
    } else {
      ElMessage.error('删除失败');
    }
  } catch (error) {
    if (error.toString() !== 'Cancel') {
      ElMessage.error('删除失败：' + error.message);
    }
  }
};

// 班主任搜索
// src/views/school/student/student.vue 中修改handleTeacherSearch方法
const handleTeacherSearch = async (query) => {
  if (!query) {
    filteredTeachers.value = [];
    return;
  }
  
  try {
    teacherLoading.value = true;
    // 从登录信息获取当前学校编号
    const loginStore = useLoginStore();
    const schoolNum = loginStore.user.number;
    
    if (!schoolNum) {
      ElMessage.error('无法获取学校信息，请重新登录');
      return;
    }
    
    // 调用教师列表API
    const response = await getTeacherListByschoolNum(schoolNum);
    filteredTeachers.value = response.data.filter(teacher => 
      teacher.teacherId.includes(query) || 
      (teacher.realName && teacher.realName.includes(query))
    );
  } catch (error) {
    ElMessage.error('搜索教师失败：' + error.message);
  } finally {
    teacherLoading.value = false;
  }
};

// 根据班级ID获取班级名称
const getClassNameByClassId = (classId) => {
  if (!classId) return '未分配班级';
  const cls = classes.value.find(c => c.id === classId);
  return cls ? cls.name : '班级已删除';
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};
</script>

<style scoped>
.class-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
  padding: 15px;
}

.class-list-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.count {
  color: #666;
  font-size: 14px;
  margin-left: 10px;
}

.text-right {
  text-align: right;
}
</style>
